#include "asprite.h"

AnimSprite * create_asprite(char *base, int x, int y, char *pic1[], ...) {
	AnimSprite * afig = (AnimSprite *) malloc(sizeof(AnimSprite));
	// create a standard sprite with first pixmap
	afig->sp = create_sprite(pic1, base,x,y);
	// count the number of variable arguments
	va_list var_args; // variable arguments
	int args = 1;
	va_start(var_args, pic1); // start reading var. args.
	while(va_arg(var_args, char **) != NULL) // next va
	args++;
	va_end(var_args); // finish using variable arguments.
	// allocate vector of pointers to pixmaps
	afig->map = (char **) malloc(args * sizeof(char *));
	// save the first pixmap
	afig->map[0] = afig->sp->map;
	va_start(var_args, pic1); // restart reading var. args.
	int i, j, wd, hg;
	for (i=1; i<args; i++) {
		char **tmp = va_arg(var_args, char **); // next va
		if ((afig->map[i] = read_xpm(tmp, &wd, &hg)) == NULL || wd != afig->sp->height || hg != afig->sp->width ) {
			// unsucess, release allocated memory
			for(j=0; j<i; j++)
			free(afig->map[j]);
			free(afig->map);
			free(afig->sp);
			free(afig);
			va_end(var_args); // finish using va. Imperative!
			return NULL;
		}
	}
	// finish using variable arguments
	va_end(var_args); 
	afig->aspeed=50;
	afig->cur_aspeed=0;
	afig->num_fig=args;
	afig->cur_fig=0;
	return afig;
} 

int animate_asprite(AnimSprite *fig, char *base, int back, int type) {
	erase_sprite(fig->sp,BLACK, base);
	if (fig->cur_aspeed==fig->aspeed)
	{	
		if(fig->cur_fig+1 == fig->num_fig)
		{
			fig->cur_fig=0;
			fig->sp->map = *(fig->map);
		}
		else
		{
			fig->cur_fig++;
			fig->sp->map = *(fig->map+fig->cur_fig);
		}
		fig->cur_aspeed=0;
	}
	else
	{
		fig->cur_aspeed++;
	}
	animate_sprite(fig->sp,base,back,type);
	return 0;
}

void destroy_asprite(AnimSprite *fig, char *base) {
	/*indexes of sprite*/
	int i,j;
	/*sets pixel [i][j] to 0*/
	for(j=fig->sp->y; j < (fig->sp->height+fig->sp->y); j++) {
		for(i=fig->sp->x; i < (fig->sp->width+fig->sp->x); i++) {
			set_pixel(i,j,0,base);
		}
	}
	/* frees memory */
	free(fig);
	return;
}
